package com.sgcc.ln.pmos.e_ln_personalcenter.activity;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.sgcc.ln.pmos.arouter.personalcenter.PersonalCenterArouterPath;
import com.sgcc.ln.pmos.common.base.BaseActivity;
import com.sgcc.ln.pmos.common.base.BaseRecyclerAdapter;
import com.sgcc.ln.pmos.common.http.HttpInterConst;
import com.sgcc.ln.pmos.common.http.HttpRequestUtils;
import com.sgcc.ln.pmos.common.http.MvcNetCallback;
import com.sgcc.ln.pmos.common.view.LineChartView;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.ln.pmos.e_ln_personalcenter.adapter.MonthAdapter;
import com.sgcc.ln.pmos.e_ln_personalcenter.bean.HistoricalPowerBean;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 历史电量查询
 */
@Route(path = PersonalCenterArouterPath.PERSONALCENTER_HISTORICALPOWER)
public class HistoricalPowerActivity extends BaseActivity {

    private TitleBar mTitleBar;
    private LinearLayout mLlYear;
    private TextView mTvYear;
    private RecyclerView mRvMonth;
    private TextView mTvTitle1;
    private TextView mTvTitle2;
    private LinearLayout llLineChart;
    private MonthAdapter mMonthAdapter;
    private List<String> month_list = new ArrayList<>();
    private int mCurrentYear;
    private int mCurrentMonth;
    private List<String> yAxis;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_historicalpower;
    }

    @Override
    protected void initViews() {
        super.initViews();
        findViewByIds();
    }

    private void findViewByIds() {
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mLlYear = (LinearLayout) findViewById(R.id.ll_year);
        mTvYear = (TextView) findViewById(R.id.tv_year);
        mRvMonth = (RecyclerView) findViewById(R.id.rv_month);
        mTvTitle1 = (TextView) findViewById(R.id.tv_title1);
        mTvTitle2 = (TextView) findViewById(R.id.tv_title2);
        llLineChart = (LinearLayout) findViewById(R.id.llLineChart);

        mTitleBar.setTitle("历史电量查询");
        mTitleBar.setRightIcon(R.mipmap.go_main, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goMainActivity();
            }
        });

        mRvMonth.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        mMonthAdapter = new MonthAdapter(mContext);

        mMonthAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                //点击事件
                mMonthAdapter.setSelectPosition(position);
                String month = (String) data;
                mCurrentMonth = Integer.parseInt(month);
                mTvTitle1.setText(mCurrentYear + "-" + mCurrentMonth);
                getEnergyHis();
            }
        });


        mRvMonth.setAdapter(mMonthAdapter);
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        if (month != 1) {
            for (int i = 1; i < month; i++) {
                month_list.add(i + "");
            }
            mMonthAdapter.addDatas(month_list);
            mTvYear.setText(year + "年");
            mMonthAdapter.setSelectPosition(calendar.get(Calendar.MONTH) - 1);
            mCurrentYear = year;
            mCurrentMonth = calendar.get(Calendar.MONTH);
        } else {
            month = 13;
            for (int i = 1; i < month; i++) {
                month_list.add(i + "");
            }
            mMonthAdapter.addDatas(month_list);
            mTvYear.setText((year - 1) + "年");
            mMonthAdapter.setSelectPosition(0);

            mCurrentYear = year - 1;
            mCurrentMonth = 1;
        }

        mRvMonth.scrollToPosition(month_list.size() - 1);

        mLlYear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initTimeSelect();
            }
        });

        mTvTitle1.setText(mCurrentYear + "-" + mCurrentMonth);
        getEnergyHis();
    }

    Calendar startDate = Calendar.getInstance();
    Calendar endDate = Calendar.getInstance();

    private void initTimeSelect() {
        //正确设置方式 原因：注意事项有说明
        Calendar calendar = Calendar.getInstance();
        // 获取当前年
        int year = calendar.get(Calendar.YEAR);
        // 获取当前月
        int month = calendar.get(Calendar.MONTH) + 1;
        startDate.set(year - 100, 1, 1);
        endDate.set(year, month, 1);
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String time = TimeUtils.date2String(date, "yyyy年");
                String year = time.substring(0, time.length() - 1);
                mCurrentYear = Integer.parseInt(year);
                mTvYear.setText(time);


                int year_int = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1;
                month_list.clear();
                if (year_int == mCurrentYear) {
                    if (month != 1) {
                        for (int i = 1; i < month; i++) {
                            month_list.add(i + "");
                        }
                        mMonthAdapter.addDatas(month_list);
                        mMonthAdapter.setSelectPosition(calendar.get(Calendar.MONTH) - 1);
                        mCurrentMonth = calendar.get(Calendar.MONTH);
                        mRvMonth.scrollToPosition(month_list.size() - 1);
                    } else {
                        month = 13;
                        for (int i = 1; i < month; i++) {
                            month_list.add(i + "");
                        }
                        mMonthAdapter.addDatas(month_list);
                        mMonthAdapter.setSelectPosition(0);
                        mRvMonth.scrollToPosition(0);
                    }
                } else {

                    for (int i = 1; i < 13; i++) {
                        month_list.add(i + "");
                    }
                    mMonthAdapter.addDatas(month_list);
                    mMonthAdapter.setSelectPosition(month_list.size() - 1);
                    mCurrentMonth = 12;
                    mRvMonth.scrollToPosition(month_list.size() - 1);
                    mTvTitle1.setText(mCurrentYear + "-" + mCurrentMonth);
                }
                getEnergyHis();
            }
        }).setType(new boolean[]{true, false, false, false, false, false})
                .setDate(getDate())
                .setDecorView((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content))
                .setRangDate(startDate, endDate)
                .build();
        pvTime.show();
    }

    private Calendar getDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(mCurrentYear, 1, 1);
        return calendar;
    }

    private void getEnergyHis() {
        String month = mCurrentMonth + "";
        month = month.length() == 1 ? "0" + month : month;
        String time = mCurrentYear + "-" + month + "-01";
        Map<String, Object> params = new HashMap<>();
        params.put("_t", System.currentTimeMillis());
        params.put("startDate", time);
        params.put("endDate", time);
        HttpRequestUtils.getInstance().request(params, HttpInterConst.USER_GETENERGYHIS, new MvcNetCallback<HistoricalPowerBean>(true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁

            }

            @Override
            public void onResponse(HistoricalPowerBean response, int id) {
                super.onResponse(response, id);
                if (response != null) {
                    if ("200".equals(response.getCode())) {
                        if (!response.getData().isEmpty()) {
                            BigDecimal bigDecimal = new BigDecimal(response.getData().get(0).getEnergy());
                            mTvTitle2.setText(bigDecimal.stripTrailingZeros().toPlainString());

                            List<BigDecimal> list = getFieldValue(response.getData().get(0));
                            yAxis = new ArrayList<>();
                            for (BigDecimal big : list) {
                                yAxis.add(big.stripTrailingZeros().toPlainString());
                            }
                            if (llLineChart.getChildCount() > 1) {
                                View childAt = llLineChart.getChildAt(1);
                                if (null != childAt) {
                                    llLineChart.removeView(childAt);
                                }
                            }
                            llLineChart.addView(new LineChartView(mContext, yAxis, false, true));
                        }else{
                            mTvTitle2.setText("0");
                            yAxis = new ArrayList<>();
                            if (llLineChart.getChildCount() > 1) {
                                View childAt = llLineChart.getChildAt(1);
                                if (null != childAt) {
                                    llLineChart.removeView(childAt);
                                }
                            }
                            llLineChart.addView(new LineChartView(mContext, yAxis, false, true));
                        }
                    } else {
                        if (!TextUtils.isEmpty(response.getMsg())) {
                            ToastUtils.showShort(response.getMsg());
                        }
                    }
                }
            }
        });
    }


    private static List<BigDecimal> getFieldValue(Object o) {
        try {
            List<BigDecimal> list = new ArrayList<>();
            String getter = "get" + "Energy";
            for (int i = 1; i < 25; i++) {
                String s1 = getter + String.valueOf(i);
                Method method = o.getClass().getMethod(s1, new Class[]{});
                Object value = method.invoke(o, new Object[]{});
                list.add(new BigDecimal((String) value));
            }
            return list;
        } catch (Exception e) {
            Log.e("TAG", "getFieldValue: " + e.toString());
        }
        return null;
    }

//    /**
//     * 是否显示点击显示数据
//     */
//    private boolean isAddMarkerView = true;
//
//    private String[] xAxisValue = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9",
//            "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"};
//    private void setLineChartData() {
//        lcLineChart.getDescription().setEnabled(false);
//        lcLineChart.setTouchEnabled(isAddMarkerView);
//        lcLineChart.setDragEnabled(isAddMarkerView);
//        lcLineChart.setPinchZoom(false);
//        lcLineChart.setScaleEnabled(false);
//        lcLineChart.setDrawGridBackground(false);
//        lcLineChart.setMaxHighlightDistance(300);
//        if (isAddMarkerView) {
//            LineMarkerView mv = new LineMarkerView(mContext);
//            mv.setChartView(lcLineChart);
//            lcLineChart.setMarker(mv);
//        }
//
//        XAxis x = lcLineChart.getXAxis();
//        x.setTextColor(Color.parseColor("#999999"));
//        x.setDrawGridLines(false);
//        x.setDrawAxisLine(true);
//        x.setPosition(XAxis.XAxisPosition.BOTTOM);
//        x.setAxisLineWidth(1);
//        x.setLabelCount(12);
//        x.setAxisLineColor(Color.parseColor("#DCDCDC"));
//        x.setValueFormatter(new IndexAxisValueFormatter(xAxisValue));
//
//        YAxis y = lcLineChart.getAxisLeft();
//        y.setTextColor(Color.parseColor("#999999"));
//        y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
//        y.setDrawAxisLine(true);
//        y.setGranularity(0.02f);
//
//        lcLineChart.getAxisRight().setEnabled(false);
//
//        Legend l = lcLineChart.getLegend();
//        l.setEnabled(false);
//
//
//    }
//
//    private void setData() {
//        if (null == yAxis)
//            yAxis = new ArrayList<>();
//
//        ArrayList<Entry> values = new ArrayList<>();
//        if (null != yAxis && yAxis.size() > 0)
//            for (int i = 0; i < yAxis.size(); i++) {
//                String s = yAxis.get(i);
//                float val = Float.parseFloat(TextUtils.isEmpty(s) ? "0" : s);
//                values.add(new Entry(i, val));
//            }
//
//        LineDataSet set1 = new LineDataSet(values, "");
//        if (!isAddMarkerView)
//            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
//        set1.setDrawValues(false);
//        set1.setLineWidth(1.5f);
//        set1.setCircleRadius(3f);
//        set1.setCircleColor(Color.parseColor("#0092FF"));
//        set1.setColor(Color.parseColor("#0092FF"));
//        set1.setCircleHoleRadius(2f);
//        set1.setDrawFilled(true);
//        Drawable drawable = ContextCompat.getDrawable(mContext, com.sgcc.ln.pmos.common.R.drawable.line_chart_fill);
//        set1.setFillDrawable(drawable);
//        set1.setFillFormatter((dataSet, dataProvider) ->
//                lcLineChart.getAxisLeft().getAxisMinimum());
//
//        lcLineChart.setData(new LineData(set1));
//
//    }
}
